<template>
  <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
    <!-- <el-form-item label="原始密码" prop="oldPassword">
      <el-input v-model="formItem.oldPassword" type="password" autocomplete="off" />
    </el-form-item> -->
    <el-form-item label="密码" prop="password" required>
      <el-input v-model="formItem.password" type="password" placeholder="请输入密码" />
    </el-form-item>
    <el-form-item label="确认新密码" prop="passwordAgain" required>
      <el-input v-model="formItem.passwordAgain" type="password" placeholder="请再次输入新密码" />
    </el-form-item>
  </el-form>
</template>

<script>
import { resetpassword } from '@neu/auth-ui/api/user'

// 定义一个表单原始项
const formItem = {
  password: '',
  oldPassword: '',
  passwordAgain: ''
}

export default {
  name: 'ResetPasswordForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formItem.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        // oldPassword: [
        //   { required: true, message: '原始密码不能为空', trigger: 'blur' },
        //   { min: 6, max: 18, message: '6~18位密码', trigger: 'blur' }
        // ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '6~18位密码', trigger: 'blur' }
        ],
        passwordAgain: [
          { required: true, message: '确认新密码不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    reset() {
      this.$refs.myform.resetFields()
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            resolve(resetpassword(this.id, this.formItem))
          } else {
            resolve(false)
          }

          this.reset()
        })
      })
    }
  }
}
</script>
